package com.gonsin.ta.logic.parse.serialize;

import com.google.gson.*;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;

import java.io.IOException;
import java.lang.reflect.Type;

public class DeserializeTypeAdapter implements JsonDeserializer<TaDeserializable> {

    @Override
    public TaDeserializable deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        JsonObject jsonObject = json.getAsJsonObject();

        JsonElement componentTypeElement = jsonObject.get("componentType");
        if(componentTypeElement == null){
            return parseCondition(jsonObject, json, context);
        } else {
            String componentType = componentTypeElement.getAsString();
            if ("NODE".equals(componentType)) {
                return context.deserialize(json, NodeSerial.class);
            } else if ("CONDITION".equals(componentType)) {
                return parseCondition(jsonObject, json, context);
            }
        }

        return null;
    }

    private TaDeserializable parseCondition(JsonObject jsonObject, JsonElement json, JsonDeserializationContext context) {

        JsonElement conditionTypeElement = jsonObject.get("conditionType");
        String conditionType = conditionTypeElement.getAsString();

        if("SWITCH".equals(conditionType)) {
            return context.deserialize(json, SwitchConditionSerial.class);
        } else if("RUN".equals(conditionType)) {
            return context.deserialize(json, RunConditionSerial.class);
        } else if("WAIT".equals(conditionType)) {
            return context.deserialize(json, WaitConditionSerial.class);
        } else if("FUTURE".equals(conditionType)) {
            return context.deserialize(json, FutureConditionSerial.class);
        }
        return null;
    }
}
